import { login, getUserProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // token从本地cookie拿
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    // token持久化
    setToken(token)
  },
  REOMVE_TOKEN: () => {
    state.token = null
    removeToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info  一进页面就发请求获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserProfile(state.token).then(response => {
        console.log(response, '首次登录进入页面时获取的数据')
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { username } = data

        commit('SET_NAME', username)
        commit('SET_USERINFO', data)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      //   removeToken() // must remove  token  first
      //   resetRouter()
      //   commit('RESET_STATE')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  async getAvatar({ commit }, id) {
    const { data } = await getUserDetailById(id)
    commit('SET_AVATAR', data.staffPhoto)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

